﻿#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QApplication>
#include <QApplication>
#include <QTextEdit>
#include <QProcess>
#include <QVBoxLayout>
#include <QWidget>
#include <QLabel>
#include <QDebug>
#include <QTextCodec>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QMessageBox>
#include <QCoreApplication>
#include <QApplication>
#include <QMainWindow>
#include <QTreeView>
#include <QStandardItemModel>
#include <QProcess>
#include <QVBoxLayout>
#include <QStringList>
#include <QRegularExpression>
#include <QRegularExpressionMatchIterator>
#include <QString>
#include <QMessageBox>
#include <QSettings>
#include <QtNetwork/QNetworkInterface>
#include <QtCore/QCoreApplication>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{


    
    ui->setupUi(this);
    loadSettings();
    //MainWindow::on_pushButton_2_clicked();
    
    
    //output.replace(" \n", "");
    //get name and group
    //GET IP AND MAC
    // QString ipmac = MainWindow::getipandmac();
    //get name and group
   // QString name = ui->lineEdit->text();
    //qDebug() << name << endl;

    //�����ļ�
    //QFile file("output.txt");
    //if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
    //    qDebug() << "Cannot open file for writing: " << file.errorString();
    //    
    //}
    //QTextStream out(&file);
    //out.setCodec("UTF-8"); // ���ñ���Ϊ UTF-8
    //out << name;


    //file.close();
   
}

MainWindow::~MainWindow()
{
    delete ui;
}

//保存按钮
bool MainWindow::on_pushButton_3_clicked() {
    name = ui->lineEdit->text();
    group = ui->lineEdit_2->text();
    DeviceName = ui->lineEdit_3->text();

    QList<Net_Info> netInfos;

    Net_Info lan;
    lan.ip = ui->lineEdit_4->text();
    lan.mac = ui->lineEdit_5->text();
    netInfos.push_back(lan);

    Net_Info wifi;
    wifi.ip = ui->lineEdit_6->text();
    wifi.mac = ui->lineEdit_7->text();
	netInfos.push_back(wifi);


    QSqlQuery querycount;
    QString id1;
    querycount.prepare(QString("SELECT COUNT(*) FROM %1").arg("imac"));

    if (!querycount.exec()) {
        qDebug() << "查询失败:" << querycount.lastError().text();
        //return -1; // 查询失败，返回 -1
    }
    if (querycount.next()) {
        int idnum = querycount.value(0).toInt()+1;
        id1 = QString::number(idnum);
    }

    if (datasave(name, group, DeviceName, netInfos))
    {
        QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), QString::fromLocal8Bit("数据添加成功。"), QMessageBox::Ok);

        emit freshData();

        return true;
    }
    else {
        QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), QString::fromLocal8Bit("数据添加失败。"), QMessageBox::Ok);
        return false;
    }

}

//保存至数据库
bool MainWindow::datasave(QString name, QString group, QString type, QList<Net_Info> NetInfos) 
{
    for (int i = 0; i < NetInfos.size(); i++)
    {
        QString strInsertInfo = QString("INSERT INTO imac(ip, mac, name, group_name, type) VALUES ('%1', '%2', '%3', '%4', '%5')")
            .arg(NetInfos[i].ip)
            .arg(NetInfos[i].mac)
            .arg(name)
            .arg(group)
            .arg(type);

        QSqlQuery query3;

		if (!query3.exec(strInsertInfo)) 
        {
			QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), QString::fromLocal8Bit("数据插入失败"), QMessageBox::Ok);
			query3.lastError().text();
			return false;
		}

    }
    return true;
}





//选择性显式下边的两个按钮。
void MainWindow::showbutton(bool outbutton,bool savebutton) {
    if (!outbutton) {
        ui->label_4->hide();
        ui->textEdit->hide();
        ui->pushButton_2->hide();
        ui->pushButton->hide();
    }
    if (!savebutton) {
        ui->pushButton_3->hide();
    }

}
void MainWindow::loadSettings() {
    QSettings settings("YourCompany", "YourApp");
    ui->lineEdit->setText(settings.value("lastInputmainwindow1").toString());
    ui->lineEdit_2->setText(settings.value("lastInputmainwindow2").toString());
    ui->lineEdit_3->setText(settings.value("lastInputmainwindow3").toString());

}

void MainWindow::saveSettings() {
    QSettings settings("YourCompany", "YourApp");
    settings.setValue("lastInputmainwindow1", ui->lineEdit->text());
    settings.setValue("lastInputmainwindow2", ui->lineEdit_2->text());
    settings.setValue("lastInputmainwindow3", ui->lineEdit_3->text());
}

//get   ip  and  mac
QString MainWindow::getipandmac()
{
    QProcess process;
    
    process.start("ipconfig", QStringList() << "/all");
    process.waitForFinished();
    QString output = QString::fromLocal8Bit(process.readAllStandardOutput());
    return output;

}

bool allLineEditsFilled(const QWidget* parent) {
    // 获取所有的 QLineEdit 子对象
    QList<QLineEdit*> lineEdits = parent->findChildren<QLineEdit*>();

    // 检查每一个 QLineEdit 是否为空
    for (QLineEdit* lineEdit : lineEdits) {
        if (lineEdit->text().isEmpty()) {
            return false;
        }
    }

    return true;
}

void MainWindow::on_pushButton_clicked()
{
    
        QList<QLineEdit*> lineEdits = findChildren<QLineEdit*>();

        // 检查每一个 QLineEdit 是否为空
        for (QLineEdit* lineEdit : lineEdits) {
            if (lineEdit->text().isEmpty()) {
                QMessageBox::warning(this, "Warning", QString::fromLocal8Bit("请完成所有内容的识别及填写"));
                return; // 如果发现空的 QLineEdit，弹出提示框并返回
            }
            
        }

    //GET name and group and Device_Name
    name = ui->lineEdit->text();
    group = ui->lineEdit_2->text();
    DeviceName = ui->lineEdit_3->text();
    youxianip = ui->lineEdit_4->text();
    youxianmac= ui->lineEdit_5->text();
    wuxianip = ui->lineEdit_6->text();
    wuxianmac = ui->lineEdit_7->text();
    //GET ip and  mac
    QString ipmac = MainWindow::getipandmac();
    //creat txt and 
    QString txtname = "infor_"+ group+"_" + name;
    QString current_address = QFileDialog::getSaveFileName(this, QString::fromLocal8Bit("选择文件夹"), txtname, "*.txt");
    if (current_address.isEmpty())  return;
    QFile file(current_address);
    if (!file.open(QFile::WriteOnly | QFile::Text))
    {
        QMessageBox::warning(this, QString::fromLocal8Bit("警告"), tr("无法打开文件output.for, 请检查!"));
        return;
    }
    QString dir = QCoreApplication::applicationDirPath();
    QTextStream out(&file);
    out << QString::fromLocal8Bit("copyright 2024. ksen_PKUNCII") << endl;
    out <<  endl;
    out <<  name << endl;
    out <<  group << endl;
    out <<  DeviceName << endl;
    out <<  youxianip << endl;
    out <<  youxianmac << endl;
    out <<  wuxianip << endl;
    out <<  wuxianmac << endl;
    out << "___________________________________"<<QString::fromLocal8Bit("详细信息")<<"___________________________________" << endl;
    out << ipmac << endl;

}


void MainWindow::on_pushButton_2_clicked()
{

    QString ipmac = MainWindow::getipandmac();
    ui->textEdit->setText(ipmac);
    std::string str = ipmac.toStdString();
    QStringList lines = ipmac.split('\n');

    QStringList filteredLines;
    for (const QString& line : lines) {
        if (line.contains(QString::fromLocal8Bit("适配器"))|| line.contains("IPv4") || line.contains(QString::fromLocal8Bit("物理地址"))) {
            filteredLines.append(line); 
        }
    }
   QString filteredString = filteredLines.join('\n');
   QString filteredString2 = filteredString.replace(QString::fromLocal8Bit("(首选)"), "");
   QStringList neironglines = filteredString2.split('\n');
   QString  mac="0";
   QString  wuxianip="0";
   QString  youxianip="0";
   for (const QString& line : neironglines) 
   {
       if (line.contains(QString::fromLocal8Bit("物理地址"))) {
          mac = line;
          int index = mac.indexOf(':');
           if (index != -1) {
               mac = mac.mid(index + 1);
           }
           mac.remove('\r');
           mac.remove(' ');
       }
       else if (line.contains("172.16.10") || line.contains("172.16.21")) {
           youxianip = line;
           int index = youxianip.indexOf(':');
           if (index != -1) {
               youxianip = youxianip.mid(index + 1);
           }
           youxianip.remove('\r');
           youxianip.remove(' ');
           ui->lineEdit_4->setText(youxianip);
           ui->lineEdit_5->setText(mac);
       }
       else if (line.contains("172.16")){
           wuxianip = line;
           int index = wuxianip.indexOf(':');
           if (index != -1) {
               wuxianip = wuxianip.mid(index + 1);
           }
           wuxianip.remove('\r');
           wuxianip.remove(' ');
           ui->lineEdit_6->setText(wuxianip);
           ui->lineEdit_7->setText(mac);
       }
       else if (line.contains(QString::fromLocal8Bit("适配器"))) {
          
           youxianip.clear();
           wuxianip.clear();
           mac.clear();
       }
   }
   QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
   for (const QNetworkInterface& interface : interfaces) 
   {
       // 获取接口名称
       QString interfaceName = interface.humanReadableName();
       // 获取物理地址（MAC 地址）
       QString macAddress = interface.hardwareAddress();
      // qDebug() << QString::fromLocal8Bit("接口名称:") << interfaceName;
       //qDebug() << QString::fromLocal8Bit("物理地址:" )<< macAddress;
       if (interfaceName.contains(QString::fromLocal8Bit("WLAN"))) {
           // 打印接口名称和物理地址
           qDebug() << QString::fromLocal8Bit("无线接口名称:") << interfaceName;
           qDebug() << QString::fromLocal8Bit("物理地址:") << macAddress;
       }
       if (interfaceName.contains(QString::fromLocal8Bit("以太网"))) {
           // 打印接口名称和物理地址
           qDebug() << QString::fromLocal8Bit("有线接口名称:") << interfaceName;
           qDebug() << QString::fromLocal8Bit("物理地址:") << macAddress;
       }
   }
   if (youxianip==0) {
       for (const QNetworkInterface& interface : interfaces)
       {
           // 获取接口名称
           QString interfaceName = interface.humanReadableName();
           // 获取物理地址（MAC 地址）
           QString macAddress = interface.hardwareAddress();
           // qDebug() << QString::fromLocal8Bit("接口名称:") << interfaceName;
            //qDebug() << QString::fromLocal8Bit("物理地址:" )<< macAddress;
           
           if (interfaceName.contains(QString::fromLocal8Bit("以太网"))) {
               // 打印接口名称和物理地址
               qDebug() << QString::fromLocal8Bit("有线接口名称:") << interfaceName;
               qDebug() << QString::fromLocal8Bit("物理地址:") << macAddress;
              // ui->lineEdit_4->setText(youxianip);
               macAddress.replace(QString(":"), QString("-"));
               macAddress = macAddress.toUpper();
               ui->lineEdit_5->setText(macAddress);
              
           }
       }
   }
   if(wuxianip==0) {
       
       for (const QNetworkInterface& interface : interfaces)
       {
           // 获取接口名称
           QString interfaceName = interface.humanReadableName();
           // 获取物理地址（MAC 地址）
           QString macAddress = interface.hardwareAddress();
           // qDebug() << QString::fromLocal8Bit("接口名称:") << interfaceName;
            //qDebug() << QString::fromLocal8Bit("物理地址:" )<< macAddress;
           if (interfaceName.contains(QString::fromLocal8Bit("WLAN"))) {
               // 打印接口名称和物理地址
               qDebug() << QString::fromLocal8Bit("无线接口名称:") << interfaceName;
               qDebug() << QString::fromLocal8Bit("物理地址:") << macAddress;
               //ui->lineEdit_6->setText(wuxianip);
               macAddress.replace(QString(":"), QString("-"));
               macAddress = macAddress.toUpper();
               ui->lineEdit_7->setText(macAddress);

           }
          
       }
   }
   return;


}


